﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DocumentsTagger.DM;
using System.IO;

namespace WinFormTagger
{
    public partial class MainWindow : Form
    {
        private MainWindowViewModel model = new MainWindowViewModel();

        public MainWindow()
        {
            InitializeComponent();
            attachEvents();
            model.init();
        }

        private void attachEvents()
        {
            model.DocumentFound += new DocumentFoundHandler(model_DocumentFound);
        }

        void model_DocumentFound(Document doc)
        {
            TreeNode location = CreatePathTree(doc.FilePath);
            TreeNode tn = new TreeNode(doc.FileName);
            tn.Name = doc.FileName;
            tn.Tag = doc;
            location.Nodes.Add(tn);
        }

        private TreeNode CreatePathTree(string PathToInsert)
        {
            string[] paths = PathToInsert.Split(new Char[] { Path.DirectorySeparatorChar });
            TreeNode currNode = null;
            foreach (string dir in paths)
            {
                if (string.IsNullOrEmpty(dir))
                {
                    continue;
                }

                if (!tv_Folders.Nodes.ContainsKey(dir))
                {
                    TreeNode newNode = new TreeNode();
                    newNode.Name = dir;
                    newNode.Text = dir;

                    if (currNode == null)
                    {
                        tv_Folders.Nodes.Add(newNode);
                    }
                    else
                    {
                        currNode.Nodes.Add(newNode);
                    }
                }

                if (currNode == null)
                {
                    currNode = tv_Folders.Nodes[dir];
                }
                else
                {
                    currNode = currNode.Nodes[dir];
                }

            }
            return currNode;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void MainWindow_Load(object sender, EventArgs e)
        {

        }

        private void tv_Folders_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode tn = e.Node ;
            if (tn != null)
            {
                Document doc = (tn.Tag as Document);
                if (doc != null)
                {
                    webBrowser.Navigate(new Uri(Path.Combine(doc.FilePath, doc.FileName)));
                }
            }
        }

        private void tv_Folders_LocationChanged(object sender, EventArgs e)
        {
            
        }
    }
}
